import { PageContainer } from "@ant-design/pro-components";
import { FC, useEffect, useRef, useState } from "react";
import { Card, DatePicker, Select, Tabs, message, Spin } from "antd";
import dayjs from "dayjs";
import Https from "@/utils/Https";
import { disabledDate } from "@/utils/common";
import styles from "./styles.less";
import SortCourse from "./Component/sortCourse"; //排课表内容
import RoomCourse from "./Component/roomCourse"; //教室维度内容
import OperationItem from "./Component/operate"; //头部更多操作
import AddWork from "./Component/addWork"; //新增排课
import EditWork from "./Component/editWork"; //查看排课
import EmptyData from "./Component/Empty"; //流程判断
import { getWeekLabel } from "../interface";
import html2canvas from "html2canvas";
import { FullscreenExitOutlined, FullscreenOutlined } from "@ant-design/icons";
const ScheduleCourse: FC<any> = () => {
  const [loading, setLoading] = useState(false);
  const [open, setOpen] = useState("");
  const [sortReload, setSortReload] = useState(false);
  //运营时间
  const [venueHours, setVenueHours] = useState({});
  //场馆列表
  const [venueList, setVenueList] = useState([]);
  //教室列表
  const [roomList, setRoomList] = useState([]);
  //场馆信息
  const [venueObj, setVenueObj] = useState({});
  //场馆接口状态
  const [venueStatus, setVenueStatus] = useState(true);
  //教室信息
  const [roomInfo, setRoomInfo] = useState({});
  //初始化日期信息
  const [defaultWeekValue, setDefaultWeekValue] = useState<any>("");
  const [defaultTime, setDefaultTime] = useState({});
  const [addWorkDate, setAddWorkDate] = useState("");
  const [workInfo, setWorkInfo] = useState({});
  const [dimension, setDimension] = useState("date");
  const [weekTimeList, setWeekTimeList] = useState([]);
  const [weekTimeInfo, setWeekTimeInfo] = useState({});
  const [activiteRoom, setActiviteRoom] = useState("");
  const [activiteTime, setActiviteTime] = useState("");
  const [full, setFull] = useState(false);
  const [isDown, setIsDown] = useState(false);
  //获取所有场馆
  const getAllVenue = async () => {
    setLoading(true);
    let res: any = await Https.get("/venue/info/queryVenueTradeHour", {}, true);
    if (res.code == 200 && res.data) {
      setVenueObj(res.data);
      setVenueList([{ ...res.data }]);
      setVenueStatus(true);
      getAllClassRoom(res.data.id);
      getWeekList(res.data.id, dayjs());
    } else {
      setVenueStatus(false);
      message.error(res.msg);
    }
    setLoading(false);
  };
  //获取所有教室列表
  const getAllClassRoom = async (id) => {
    setLoading(true);
    let res = await Https.get(
      "/course/sched/classRoomAllList?venueId=" + id,
      {},
      true
    );
    setLoading(false);
    if (res.code == 200) {
      let objList = [];
      if (res.data.length > 0) {
        res.data.map((item) =>
          objList.push({ ...item, label: item.classRoomName, key: item.id })
        );
        setRoomInfo(objList[0]);
        setActiviteRoom(objList[0].key);
      }
      setRoomList(objList);
    } else {
      setRoomList([]);
    }
  };
  //获取本周日期排序
  const getWeekList = async (id, defaultWeekValue) => {
    let params = {
      weekType: "2",
      pramDate: dayjs(defaultWeekValue).format("YYYY-MM-DD"),
      venueId: id,
    };
    setLoading(true);
    let res: any = await Https.post("/course/sched/timeWeek", params, true);
    if (res.code == 200) {
      let objList: any = [];
      if (res.data.length > 0) {
        res.data.map((item) => {
          objList.push({
            ...item,
            label: getWeekLabel(item.date),
            key: item.date,
          });
        });
        setActiviteTime(objList[0].key);
        setWeekTimeInfo(objList[0]);
        setWeekTimeList(objList);
      } else {
        setWeekTimeList([]);
      }
    } else {
      setWeekTimeList([]);
      message.error(res.msg);
    }
    setLoading(false);
  };
  //下载图片
  const downImg = () => {
    setIsDown(true);
    setLoading(true);
    setTimeout(() => {
      let scrollableArea = document.getElementById("scheduleDown");
      if (scrollableArea) {
        html2canvas(scrollableArea)
          .then((canvas) => {
            const link = document.createElement("a");
            link.href = canvas.toDataURL();
            link.setAttribute(
              "download",
              venueObj.venueName +
                "_" +
                roomInfo.classRoomName +
                "_" +
                dayjs(defaultWeekValue).format("YYYY-MM-DD 第wo") +
                "排课表" +
                ".png"
            );
            link.style.display = "none";
            document.body.appendChild(link);
            link.click();
            setLoading(false);
            setIsDown(false);
          })
          .catch((error) => {
            setLoading(false);
            setIsDown(false);
          });
      } else {
        message.error("当前周课表暂无数据");
        setLoading(false);
        setIsDown(false);
      }
    }, 500);
  };
  useEffect(() => {
    setDefaultWeekValue(dayjs());
    setTimeout(() => {
      setDefaultTime({
        startTime: dayjs().startOf("week").format("YYYY-MM-DD"),
        endTime: dayjs().endOf("week").format("YYYY-MM-DD"),
      });
    }, 500);
    getAllVenue();
  }, []);
  return (
    <div className={full ? styles.FullContainer : ""}>
      <Spin spinning={loading}>
        <PageContainer
          title="课程表"
          className={styles.ScheduleCourse}
          extra={
            <OperationItem
              defaultTime={defaultTime}
              onSuccess={() => {
                setSortReload(!sortReload);
              }}
              dimension={dimension}
              updateDimension={() => {
                let currentDimension = dimension == "date" ? "room" : "date";
                setDimension(currentDimension);
                // setVenueObj({});
                // setRoomList([]);
                // setRoomInfo({});
                // setWeekTimeList([]);
                setDefaultWeekValue(dayjs());
                setTimeout(() => {
                  setDefaultTime({
                    startTime: dayjs().startOf("week").format("YYYY-MM-DD"),
                    endTime: dayjs().endOf("week").format("YYYY-MM-DD"),
                  });
                  //getAllVenue();
                }, 500);
              }}
              onDownImg={() => {
                downImg();
              }}
            />
          }
        >
          <Card
            title={
              <>
                {/* <Select
                  placeholder="请选择场馆"
                  value={venueObj.id}
                  onChange={(val) => {
                    let obj = venueList.filter(function (o) {
                      return o.id == val;
                    })[0];
                    if (dimension == "date") {
                      getAllClassRoom(obj.id);
                    } else {
                      getWeekList(obj.id, defaultWeekValue);
                    }
                    setVenueObj(obj);
                  }}
                  style={{ width: "200px" }}
                >
                  {venueList &&
                    venueList.map((item, index) => (
                      <Select.Option key={item.id} value={item.id}>
                        {item.venueName}
                      </Select.Option>
                    ))}
                </Select> */}
                <DatePicker
                  style={{ marginLeft: "20px" }}
                  format={`YYYY-MM-DD 第wo`}
                  allowClear={false}
                  picker="week"
                  value={defaultWeekValue}
                  renderExtraFooter={() => {
                    return (
                      <div style={{ width: "100%", textAlign: "center" }}>
                        <a
                          onClick={() => {
                            setDefaultWeekValue(dayjs());
                            setDefaultTime({
                              startTime: dayjs()
                                .startOf("week")
                                .format("YYYY-MM-DD"),
                              endTime: dayjs()
                                .endOf("week")
                                .format("YYYY-MM-DD"),
                            });
                            if (dimension == "room") {
                              getWeekList(venueObj.id, dayjs());
                            }
                          }}
                        >
                          回到今天
                        </a>
                      </div>
                    );
                  }}
                  onChange={(date, dateString: string) => {
                    setDefaultWeekValue(date);
                    let currentDate = dateString.split(" ")[0];
                    let startTime = dayjs(currentDate)
                      .startOf("week")
                      .format("YYYY-MM-DD");
                    let endTime = dayjs(currentDate)
                      .endOf("week")
                      .format("YYYY-MM-DD");
                    setDefaultTime({ startTime, endTime });
                    if (dimension == "room") {
                      getWeekList(venueObj.id, date);
                    }
                  }}
                />
              </>
            }
            style={{ marginTop: "20px" }}
          >
            <EmptyData
              venueStatus={venueStatus}
              venueList={venueList}
              roomList={roomList}
              venueObj={venueObj}
              dimension={dimension}
              onVenue={() => {
                getAllVenue();
              }}
            ></EmptyData>
            {dimension == "date" && venueObj.id && roomList.length > 0 && (
              <div id="FullBox" className={full ? styles.tabFixed : ""}>
                <div className={styles.tabFlex}>
                  <Tabs
                    onChange={(val) => {
                      let obj = roomList.filter(function (o) {
                        return o.id == val;
                      })[0];
                      setActiviteRoom(val);
                      setRoomInfo(obj);
                    }}
                    activeKey={activiteRoom}
                    type="card"
                    items={roomList}
                  />
                  <div className={styles.FullIcon}>
                    {full ? (
                      <FullscreenExitOutlined
                        title="取消全屏"
                        onClick={() => {
                          setFull(!full);
                        }}
                      />
                    ) : (
                      <FullscreenOutlined
                        title="全屏"
                        onClick={() => {
                          setFull(!full);
                        }}
                      />
                    )}
                  </div>
                </div>
                <div
                  id="scheduleDown"
                  style={{
                    width: isDown ? "1603px" : "100%",
                  }}
                >
                  <SortCourse
                    roomInfo={roomInfo}
                    venueObj={venueObj}
                    defaultWeekValue={defaultWeekValue}
                    defaultTime={defaultTime}
                    sortReload={sortReload}
                    isFull={full}
                    isScroll={!isDown}
                    addWork={(type, index, date, info) => {
                      let getHourse = JSON.parse(venueObj.venueTradeHours);
                      let venueTime = getHourse.filter(function (o) {
                        return o.days.indexOf(index) > -1;
                      });
                      if (type == "add") {
                        if (venueTime.length == 0) {
                          message.error("该场馆下当天没有运营时间");
                        } else {
                          let venueStart = venueTime[0].time.split("-")[0];
                          let venueEnd = venueTime[0].time.split("-")[1];
                          setVenueHours({ venueStart, venueEnd });
                          setAddWorkDate(date);
                          setOpen(type);
                        }
                      } else if (type == "edit") {
                        if (venueTime.length == 0) {
                          setVenueHours({
                            venueStart: "00:00",
                            venueEnd: "23:00",
                          });
                          setAddWorkDate(date);
                          setOpen(type);
                          setWorkInfo({ ...info, isExpired: 1 });
                        } else {
                          let venueStart = venueTime[0].time.split("-")[0];
                          let venueEnd = venueTime[0].time.split("-")[1];
                          setVenueHours({ venueStart, venueEnd });
                          setAddWorkDate(date);
                          setOpen(type);
                          setWorkInfo({
                            ...info,
                            isExpired:
                              roomInfo.roomStatus == "0" ? info.isExpired : 1,
                          });
                        }
                      }
                    }}
                  />
                </div>
              </div>
            )}
            {dimension == "room" && venueObj.id && (
              <div id="FullBox" className={full ? styles.tabFixed : ""}>
                <div className={styles.tabFlex}>
                  <Tabs
                    onChange={(val) => {
                      let obj = weekTimeList.filter(function (o) {
                        return o.date == val;
                      })[0];
                      setActiviteTime(val);
                      setWeekTimeInfo(obj);
                    }}
                    type="card"
                    activeKey={activiteTime}
                    items={weekTimeList}
                  />
                  <div className={styles.FullIcon}>
                    {full ? (
                      <FullscreenExitOutlined
                        title="取消全屏"
                        onClick={() => {
                          setFull(!full);
                        }}
                      />
                    ) : (
                      <FullscreenOutlined
                        title="全屏"
                        onClick={() => {
                          setFull(!full);
                        }}
                      />
                    )}
                  </div>
                </div>
                <RoomCourse
                  weekTimeInfo={weekTimeInfo}
                  venueObj={venueObj}
                  sortReload={sortReload}
                  isFull={full}
                  addWork={(type, info) => {
                    let getHourse = JSON.parse(venueObj.venueTradeHours);
                    let index =
                      dayjs(weekTimeInfo.date).day() == 0
                        ? 7
                        : dayjs(weekTimeInfo.date).day();
                    let venueTime = getHourse.filter(function (o) {
                      return o.days.indexOf(index) > -1;
                    });
                    if (type == "add") {
                      if (venueTime.length == 0) {
                        message.error("该场馆下当天没有运营时间");
                      } else {
                        let venueStart = venueTime[0].time.split("-")[0];
                        let venueEnd = venueTime[0].time.split("-")[1];
                        setVenueHours({ venueStart, venueEnd });
                        setAddWorkDate(weekTimeInfo.date);
                        setRoomInfo({ ...info, id: info.classRoomId });
                        setOpen(type);
                      }
                    } else if (type == "edit") {
                      if (venueTime.length == 0) {
                        setVenueHours({
                          venueStart: "00:00",
                          venueEnd: "23:00",
                        });
                        setAddWorkDate(weekTimeInfo.date);
                        setOpen(type);
                        setWorkInfo({ ...info, isExpired: 1 });
                      } else {
                        let venueStart = venueTime[0].time.split("-")[0];
                        let venueEnd = venueTime[0].time.split("-")[1];
                        setVenueHours({ venueStart, venueEnd });
                        setAddWorkDate(weekTimeInfo.date);
                        setOpen(type);
                        setWorkInfo({
                          ...info,
                        });
                      }
                    }
                  }}
                />
              </div>
            )}
          </Card>
          {/* 新增排课 */}
          <AddWork
            venueHours={venueHours}
            venueObj={venueObj}
            roomInfo={roomInfo}
            open={open == "add"}
            workDate={addWorkDate}
            onSuccess={() => {
              setSortReload(!sortReload);
              setOpen("");
            }}
            onClose={() => {
              setOpen("");
            }}
          ></AddWork>
          {/* 查看排课 */}
          <EditWork
            venueHours={venueHours}
            open={open == "edit"}
            info={workInfo}
            workDate={addWorkDate}
            onSuccess={() => {
              setSortReload(!sortReload);
              setOpen("");
            }}
            onClose={() => {
              setOpen("");
            }}
          ></EditWork>
        </PageContainer>
      </Spin>
    </div>
  );
};
export default ScheduleCourse;
